package com.example.rpsm_property.service;

import com.example.rpsm_property.mapper.BuildingMapper;
import com.example.rpsm_property.pojo.Building;
import com.example.rpsm_property.pojo.PageResult;
import com.example.rpsm_property.pojo.ResponsePojo;
import com.example.rpsm_property.utils.StringUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;


@Service
@Transactional
public class BuildingServiceImpl implements BuildingService {
    @Autowired
    BuildingMapper buildingMapper;

    @Override
    public List<Building> buildingsOfUsed() {
        return buildingMapper.buildingsOfStatus(1);

    }

    @Override
    public PageResult<Building> PageOfBuilding(int current, int
            size) {
        PageHelper.startPage(current, size);
        List<Building> page = buildingMapper.buildingsOfStatus(0);
        return PageResult.restPage((Page<Building>) page);
    }

    @Autowired
    BuildingServiceImpl buildingService;

    @Override
    public int insertBuilding(Building building) throws
            DuplicateKeyException {
        return buildingMapper.insertBuilding(building);
    }

    @Override
    public int changeBuildingStatus(List<Integer> idList, Integer
            status) {
        return buildingMapper.changeBuildingStatus(idList, status);
    }

    @Transactional
    @Override
    public int insertBuildings(Building building, List<Building> buildings, int size) {
        // 清空 buildings 列表，防止残留数据
        buildings.clear();
        int result = -1;
        try {
            // 根据建筑编码和建筑名称是否包含数字，决定使用哪种方式
            if (isContainsNumber(building.getBuilding_code()) && isContainsNumber(building.getBuilding_name())) {
                // 如果建筑编码和建筑名称都包含数字，使用替换方法
                result = insertBuildingsWithReplace(building, buildings, size);
            } else {
                // 如果建筑编码或名称不包含数字，使用递增方法
                result = insertBuildingsWithSimpleIncrement(building, buildings, size);
            }
        } catch (DuplicateKeyException e) {
            // 异常处理
            System.out.println("建筑编号重复，原因：" + e.getMessage());
            throw new DuplicateKeyException("建筑编号重复。" + e.getMessage());
        }
        return result;
    }

    // 方法 1：基于简单递增生成建筑编码和名称
    private int insertBuildingsWithSimpleIncrement(Building building, List<Building> buildings, int size) {
        int result = -1;
        try {
            for (int i = 1; i <= size; i++) {
                Building tempBuilding = building.clone();
                // 生成新的建筑编码和建筑名称
                String code = generateBuildingString(building.getBuilding_code(), i);
                String name = generateBuildingString(building.getBuilding_name(), i);

                // 设置递增后的建筑编码和名称
                tempBuilding.setBuilding_code(code);
                tempBuilding.setBuilding_name(name);

                buildings.add(tempBuilding);
            }
            result = buildingMapper.insertBuildings(buildings);
        } catch (CloneNotSupportedException e) {
            System.out.println("克隆建筑对象失败：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }


    // 方法 2：基于替换编码中的数字来生成建筑编码和名称
    private int insertBuildingsWithReplace(Building building, List<Building> buildings, int size) {
        // 不直接修改建筑对象，避免相同编码和名称
        String code = building.getBuilding_code();
        String name = building.getBuilding_name();

        // 替换建筑编码中的数字
        code = replaceNumberInString(code);
        building.setBuilding_code(code);

        // 替换建筑名称中的数字
        name = replaceNumberInString(name);
        building.setBuilding_name(name);
        buildings.add(building); // 添加第一个建筑记录
        int result = -1;
        try {
            for (int i = 1; i < size; i++) {
                Building tempBuilding = building.clone(); // 克隆原始建筑对象

                // 在每次插入时生成新的建筑编码和名称，避免重复
                String tempCode = generateBuildingString(building.getBuilding_code(), i + 1); // i + 1 确保递增
                tempBuilding.setBuilding_code(tempCode);

                String tempName = generateBuildingString(building.getBuilding_name(), i + 1);
                tempBuilding.setBuilding_name(tempName);

                buildings.add(tempBuilding); // 添加新的建筑记录
            }
            result = buildingMapper.insertBuildings(buildings); // 批量插入数据库
        } catch (CloneNotSupportedException e) {
            System.out.println("克隆建筑对象失败：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    // 公共方法：判断字符串中是否包含数字
    private boolean isContainsNumber(String str) {
        return str.matches(".*\\d+.*"); // 如果包含数字，则返回 true
    }

    // 通用方法：替换字符串中的数字部分
    private String replaceNumberInString(String str) {
        String numberPart = StringUtil.getNumberFromString(str);  // 提取数字部分
        return str.replaceAll("\\d+$", StringUtil.numberToLen2String(Integer.parseInt(numberPart))); // 替换末尾数字
    }

    // 通用方法：根据数字递增生成建筑编码或名称
    private String generateBuildingString(String buildingString, int index) {
        // 如果字符串包含数字，提取并递增数字
        if (buildingString.matches(".*\\d+.*")) {
            String numberPart = StringUtil.getNumberFromString(buildingString);
            String prefix = buildingString.replaceAll("\\d+", "");

            return prefix + String.format("%02d", Integer.parseInt(numberPart) + index - 1);  // index-1 让递增从01开始
        } else {
            // 如果没有数字，直接拼接递增数字
            return buildingString + String.format("%02d", index);  // 生成 BLD01、BLD02 等
        }
    }


}


